<?php

$cs = &getService('CitiesService');
$dbs = &getService('DBService');
$query = 'select region, COUNT(*) from search_queries where region != \'\' group by region';
$regActivityStat = $dbs->executeQuery($query);

$total = 0;

for($i = 0; $i < count($regActivityStat); $i++){
	$total += $regActivityStat[$i][1];	
}

$im = imagecreatefrompng('region-activities-bkg.png');
$orange = imagecolorallocate($im, 252, 100, 4);
$black = imagecolorallocate($im, 0, 0, 0); 

$img_width = 421;
$img_height = 215;
$count = count($cs->citiesList);

$bar_width = round(($img_width - 49) / $count);

$x1 = 44;
$x2 = $x1 + $bar_width; 
$y2 = 220;

for($i = 0; $i < $count; $i++){
	$city = $cs->citiesList[$i];
	$value = getActivityValue($city->key, &$regActivityStat, $total);
	$bar_height = round($value * 215 / 100);
	$y1 = $y2 - $bar_height;
	
	imagefilledrectangle($im, $x1, $y1, $x2, $y2, $orange);
	if($value > 0){
		imagettftext($im, 8, 0, $x1 + 2, $y1 - 3, $black, 'arial.ttf', $value . '%');
	}	
	imagettftext($im, 8, 270, $x1 + 4, $y2 + 6, $black, 'arial.ttf', win2utf($city->name));
	
	$x1 = $x2 + 2;
	$x2 = $x1 + $bar_width;
}

imagepng($im, 'region-activities.png');
imagedestroy($im);

function getActivityValue($city, $data, $total){
	$value = 0;
	for($i = 0; $i < count($data); $i++){
		if($data[$i][0] == $city){
			$value = $data[$i][1];			
			$data[$i] = null;
			reset($data);
			break; 
		}		
	}	
	return round($value / $total * 100);
}
?>